package com.ceadeal.admin.web.article;

import com.ceadeal.admin.common.consts.Constant;
import com.ceadeal.admin.entity.Article;
import com.ceadeal.admin.service.article.ArticleService;
import com.ceadeal.admin.vo.param.SearchParams;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.MessageFormat;

/**
 * 功能描述: 文章web
 * @param
 * @return
 * @throws
 *
 * @author Yzw
 * @date 2017-4-3 20:37:43
 */
@Controller
@RequestMapping("/article")
public class ArticleController {

    private static final Logger log = LoggerFactory.getLogger(ArticleController.class);

    @Autowired
    private ArticleService articleService;

    @GetMapping("/list")
    public String list() {
        return "/article/list";
    }

    @ResponseBody
    @PostMapping("/listData")
    public Object listData(SearchParams sp) {
        return this.articleService.findByPaging(sp);
    }

    @GetMapping("/view")
    public String view(HttpServletRequest request, Long id) {
        Article article = this.articleService.find(id);
        request.setAttribute("article", article);
        return "/article/view";
    }

    @GetMapping("/edit")
    public String edit(HttpServletRequest request, Long id) {
        Article article = new Article();
        if (id != null) {
            article  = this.articleService.find(id);
        }
        request.setAttribute("article", article);
        return "/article/edit";
    }

    @PostMapping("/save")
    public String save(Article article, RedirectAttributes redirectAttributes) {
        try {
            this.articleService.saveHandler(article);
            redirectAttributes.addFlashAttribute("flashMessage", Constant.OPERATE_SUCCESS);
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("flashMessage", Constant.OPERATE_ERROR);
            log.error(e.getMessage());
        }
        return "redirect:/article/list";
    }

    @GetMapping("/download")
    public void download(HttpServletRequest request, HttpServletResponse response, Long id) {
        Article article = this.articleService.find(id);
        if (article == null) {
            return;
        }

        String content = article.getContent();
        String fileName = article.getTitle() + ".md";
        String filePath = MessageFormat.format("{0}/download/tmp/", request.getServletContext().getRealPath("/"));
        String fullPath = MessageFormat.format("{0}{1}", filePath, fileName);

        // 写入本地临时文件
        File tmpFile = new File(fullPath);
        try {
            FileUtils.writeStringToFile(tmpFile, content, Charset.forName("UTF-8"));
        } catch (IOException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }

        // 设置响应头
        try {
            response.setContentType("multipart/form-data;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage());
        }

        InputStream is = null; // 输入流
        OutputStream os = null; // 输出流

        try {
            is = new FileInputStream(fullPath);
            os = response.getOutputStream();
            byte[] b = new byte[1024];
            int len;
            while ((len = is.read(b)) > 0) {
                os.write(b, 0, len);
            }
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            // 关闭流
            try {
                if (is != null) {
                    is.close();
                }
                if (os != null) {
                    os.close();
                }
                // 删除临时文件
                FileUtils.forceDelete(tmpFile);
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
    }

}
